package com.tjc.ratelimit;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Expiry;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.concurrent.TimeUnit;

public class CaffineTest {
    public static void main(String[] args) throws InterruptedException {
        LoadingCache<String, Integer> cache = Caffeine
                .newBuilder()
                .initialCapacity(1)
                .maximumSize(100)
                .expireAfter(new Expiry<String, Integer>() {
                    @Override
                    public long expireAfterCreate(@NonNull String s, @NonNull Integer integer, long l) {
                        return TimeUnit.MILLISECONDS.toNanos(2000);
                    }

                    @Override
                    public long expireAfterUpdate(@NonNull String s, @NonNull Integer integer, long l, @NonNegative long l1) {
                        return l1;
                    }

                    @Override
                    public long expireAfterRead(@NonNull String s, @NonNull Integer integer, long l, @NonNegative long l1) {
                        return l1;
                    }
                }).build(new CacheLoader<String, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull String s) throws Exception {
                        return -1;
                    }
                });

        cache.put("key", 1);
        System.out.println(cache.get("key"));
        Thread.sleep(1000);
        System.out.println(cache.get("key"));
        Thread.sleep(1000);
        System.out.println(cache.get("key"));
    }
}
